$(function () {
    let layer = layui.layer;
    let form = layui.form;
    let q = {
        key: '',
        type: '',
        state: '',
        page: '',
        perpage: 5
    }
    getList(q);

    // 封装页面渲染
    function getList(q) {
        $.ajax({
            url: '/admin/article/query',
            type: 'get',
            data: q,
            success: (res) => {
                // console.log(res.data);
                let htmlStr = template("tpl-table", res.data)
                $("tbody").html(htmlStr)
                renderPage(res.data.totalCount);
            }
        })
    }

    // 初始化分类

    initCate();

    function initCate() {
        $.ajax({
            url: '/admin/category/list',
            type: 'get',
            data: {},
            success: (res) => {
                // console.log(res.data);
                let htmlStr = template("tpl-cate", res)
                $("[name=type]").html(htmlStr);
                form.render();
            }
        })
    }

    // 筛选
    $("#form-search").on("submit", function (e) {
        e.preventDefault();

        // 获取
        let key = $("[name=key]").val().trim();
        let type = $("[name=type]").val()
        let state = $("[name=state]").val()
        // 赋值
        q.key = key;
        q.type = type;
        q.state = state;
        console.log(q.key, q.type, q.state);

        getList(q);
        // $("[name=key]").val(' ');
    })

    // 分页
    let laypage = layui.laypage;

    function renderPage(total) {
        laypage.render({
            elem: 'pageBox',
            count: total,
            limit: q.perpage,
            curr: q.page,

            layout: ['count', 'limit', 'prev', 'page', 'next', 'skip'],
            limits: [5, 10, 20, 30],
            jump: function (obj, first) {
                // console.log(obj, first);
                q.page = obj.curr;
                q.perpage = obj.limit
                // q.pagenum = ;

                if (!first) {
                    getList(q);
                }
            }
        })
    }

    // 删除
    $("tbody").on("click", ".btn-delete", function () {
        let id = $(this).attr("data-id")
        $.ajax({
            url: '/admin/article/delete',
            type: 'post',
            data: {
                id: id
            },
            success: (res) => {
                console.log(res);
                if (res.code !== 200) {
                    return lauer.msg(res.msg, {
                        icon: 5
                    })
                }
                layer.msg("恭喜您，文章删除成功！", {
                    icon: 6
                })
                getList(q);
            }
        })
    })
})